package com.bigfire.dtm.core.web.facade.impl;

import com.bigfire.dtm.api.dto.req.user.CreateUserReqDTO;
import com.bigfire.dtm.api.dto.resp.user.UserDetailRespDTO;
import com.bigfire.dtm.api.web.facade.UserOpsFacade;
import com.bigfire.dtm.core.query.handler.user.UserInfoTranslator;
import com.bigfire.dtm.domain.user.command.CreateUserCommand;
import com.bigfire.dtm.domain.user.command.QueryUserByIdCommand;
import com.bigfire.dtm.domain.user.vo.UserInfoVO;
import com.bigfire.dtm.shared.common.ArgsValid;
import com.bigfire.dtm.shared.common.ResponseWrapper;
import com.bigfire.dtm.shared.enums.ResponseCodeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.commandhandling.gateway.CommandGateway;
import org.axonframework.queryhandling.QueryGateway;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;

/**
 * 月结实现接口
 * @author Damon S.
 * @version v1.0.1
 * @date 2019年10月30日 16:07
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "用户操作")
public class UserOpsFacadeImpl implements UserOpsFacade {

    private final CommandGateway commandGateway;
    private final QueryGateway queryGateway;
    private final UserInfoTranslator translator;


    @Override
    @ArgsValid
    @ApiOperation(value = "新建用户", notes = "新建用户")
    public ResponseWrapper<Long> create(CreateUserReqDTO createUserReqDTO) {
        CreateUserCommand command = CreateUserCommand.builder()
                .username(createUserReqDTO.getUsername())
                .password(createUserReqDTO.getPassword())
                .email(createUserReqDTO.getEmail()).build();

        return new ResponseWrapper<>(
                commandGateway.sendAndWait(command)
        );
    }


    @Override
    @ApiOperation(value = "获取用户详情", notes = "查看指定ID的用户详情")
    public ResponseWrapper<UserDetailRespDTO> findByUserId(@PathVariable("userId")Long userId) {
        QueryUserByIdCommand command =
                QueryUserByIdCommand.builder()
                .userId(userId).build();

        CompletableFuture<UserInfoVO> future =
                queryGateway.query(command, UserInfoVO.class);

        ResponseWrapper<UserDetailRespDTO> response;
        try {
            if (UserInfoVO.EMPTY.equals(future.get())) {
                return new ResponseWrapper<>(
                                ResponseCodeEnum.EMPTY_RESULTS
                        );
            }
            response = new ResponseWrapper<>(
                    translator.toUserResp(future.get())
            );
        } catch (Exception e) {
            log.error("=========查询用户信息失败：" + e.toString());
            response = new ResponseWrapper<>(
                    ResponseCodeEnum.INTERNAL_ERROR
            );
        }
        return response;
    }
}
